<template>
    <div class="contion">
        <div>
            <p><el-input v-model="title" placeholder="请输入您要发布的内容" style="width: 200px"/></p>
            <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :auto-upload="false"
          >
            <template #trigger>
              <el-button type="primary">选择图片/视频</el-button>
            </template>
          </el-upload>
            <el-button @click="submitData">发布</el-button>
          </div>

          <hr>
          <div>
            <h2>文件上传</h2>
            <input type="file" @change="handleFileChange" />
            <el-button @click="uploadFile" :disabled="!file">上传文件</el-button>
            <div v-if="progress > 0">
              上传进度: {{ progress }}%
            </div>
            <div v-if="message">{{ message }}</div>
          </div>
          <el-button @click="back" style="width:100px;">返回</el-button>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import http from '../http';
import { ElMessage } from 'element-plus';
const router = useRouter();


const uploadRef = ref()

const submitUpload = () => {
  uploadRef.value.submit()
}
// 定义响应式数据
const title = ref('');
const image = ref('');
const userid = localStorage.getItem('userid');
const message = ref('');

const data = {
      title: title.value,
      image: image.value,
      userid: userid,
    };

const submitData = () =>{
    http.post("http://127.0.0.1:8000/sendadd/", data).then(res=>{
        console.log(res.data)
        message.value = res.data.msg
    })
}

const back = () =>{
    router.back();
}

// 定义响应式数据
const file = ref(null); // 选择的文件
const fileName = ref(''); // 文件名
const chunkSize = ref(1 * 1024 * 1024); // 每个文件块的大小（1MB）
const totalChunks = ref(0); // 文件总块数
const progress = ref(0); // 上传进度
const messages = ref(''); // 上传结果消息
const maxConcurrentUploads = ref(3); // 最大并发上传数
const uploadQueue = ref([]); // 上传队列

// 处理文件选择
const handleFileChange = (event) => {
  file.value = event.target.files[0];
  fileName.value = file.value.name;
  totalChunks.value = Math.ceil(file.value.size / chunkSize.value);
  uploadQueue.value = Array.from({ length: totalChunks.value }, (_, i) => i);
};

// 上传文件块
const uploadChunk = async (chunkIndex) => {
  const start = chunkIndex * chunkSize.value;
  const end = Math.min(start + chunkSize.value, file.value.size);
  const chunk = file.value.slice(start, end);

  const formData = new FormData();
  formData.append('file', chunk);
  formData.append('fileName', fileName.value);
  formData.append('currentChunk', chunkIndex);
  formData.append('totalChunks', totalChunks.value);

  try {
    await axios.post('http://127.0.0.1:8000/uploads/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    updateProgress(chunkIndex);
    messages.value = `上传中... ${progress.value}%`;
  } catch (error) {
    console.error(`上传块 ${chunkIndex} 失败:`, error);
    retryChunk(chunkIndex); // 重试失败的块
  }
};

// 更新进度
const updateProgress = (chunkIndex) => {
  progress.value = Math.round(((chunkIndex + 1) / totalChunks.value) * 100);
};

// 重试失败的块
const retryChunk = (chunkIndex) => {
  setTimeout(() => {
    uploadChunk(chunkIndex);
  }, 1000); // 1秒后重试
};

// 上传文件
const uploadFile = async () => {
  if (!file.value) {
    messages.value = '请选择一个文件！';
    return;
  }

  messages.value = '开始上传...';
  progress.value = 0;

  // 并发控制
  const concurrentUploads = [];
  while (uploadQueue.value.length > 0) {
    const chunkIndex = uploadQueue.value.shift();
    concurrentUploads.push(uploadChunk(chunkIndex));

    if (concurrentUploads.length >= maxConcurrentUploads.value) {
      await Promise.race(concurrentUploads);
      concurrentUploads.shift();
    }
  }

  await Promise.all(concurrentUploads);
  messages.value = '上传成功！';
};
</script>

<style scoped>
.contion{
    display: flex;
    flex-direction: column;
    justify-content: center;
    vertical-align: middle;
}
</style>